﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.UI.XProperty
{
    /// <summary>
    /// XPropertyDescriptionCache管理类
    /// </summary>
    public class XPropertyDescriptionCache
    {
        private Dictionary<Type, List<XPropertyDescription>> _dict;


        private static XPropertyDescriptionCache s_instance;
        private static object s_lockObj = new object();

        public static XPropertyDescriptionCache Instance
        {
            get
            {
                if(s_instance == null)
                {
                    lock (s_lockObj)
                    {
                        if (s_instance == null)
                        {
                            s_instance = new XPropertyDescriptionCache();
                        }
                    }
                }
                return s_instance;
            }
        }

        public XPropertyAttribute XPropertyAttribute { get; private set; }
        public PropertyInfo PropertyInfo { get; private set; }
        private object _lockObj = new object();

        private XPropertyDescriptionCache()
        {
            _dict = new Dictionary<Type, List<XPropertyDescription>>();
        }

        public List<XPropertyDescription> Get(Type type)
        {
            if (_dict.ContainsKey(type))
            {
                return _dict[type];
            }
            else
            {
                lock (_lockObj)
                {
                    List<XPropertyDescription> lst = new List<XPropertyDescription>();

                    PropertyInfo[] propertyArr = type.GetProperties();

                    for (int index = 0; index < propertyArr.Length; index++)
                    {
                        PropertyInfo propertyInfo = propertyArr[index];
                        XPropertyAttribute xProperty = propertyInfo.GetCustomAttribute<XPropertyAttribute>(true);
                        if (xProperty != null && xProperty.IsDeprecated == false)
                        {
                            lst.Add(new XProperty.XPropertyDescription(xProperty, propertyInfo));
                        }
                    }
                    _dict.Add(type, lst);
                    return lst;
                }
            }
        }

        public void Clear()
        {
            _dict.Clear();
        }
    }
}
